package com.wgchao.authmanager.domain.model;

import com.wgchao.authmanager.domain.params.AssignInfo;
import com.wgchao.authmanager.domain.repository.HandleRepository;
import com.wgchao.authmanager.domain.repository.ProjectRepository;
import com.wgchao.authmanager.domain.repository.RoleAuthoRepository;
import com.wgchao.authmanager.domain.repository.RoleRepository;
import com.wgchao.authmanager.infrastructure.exception.ObjectDisabledException;
import com.wgchao.authmanager.infrastructure.exception.ObjectNotExistException;
import com.wgchao.authmanager.infrastructure.exception.ObjectNotLegalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @作者：wgchao
 * @时间：20:57 2020/4/28 0028
 * @用途：对角色进行授权
 **/
@Service
public class AssignRoleDoaminService {
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private HandleRepository handleRepository;
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private RoleAuthoRepository roleAuthoRepository;

    public void assignAuthosToRole(String agencyCode, String roleName, List<AssignInfo> assignInfos, String operator){
        Role role = roleRepository.get(new RoleIdentity(agencyCode, roleName));
        if(role == null){
            throw new ObjectNotExistException(roleName+"角色不存在");
        }
        if(!role.normal()){
            throw new ObjectDisabledException(roleName+"角色不可用");
        }
        List<AuthoInfo> authoInfos = new ArrayList<>();
        for(AssignInfo assignRoleInfo : assignInfos){
            if(assignRoleInfo.getHandles()==null || assignRoleInfo.getHandles().isEmpty()){
                throw new ObjectNotLegalException("资源授权必须对应操作资源");
            }
            Project project = projectRepository.get(assignRoleInfo.getProjectIdentify());
            if(project == null){
                throw new ObjectNotExistException("项目资源不存在");
            }
            MenuResource menuResource = project.findMenu(assignRoleInfo.getMenuIdnetify());
            if(menuResource == null){
                throw new ObjectNotExistException("菜单资源不存在");
            }
            for(String handleId : assignRoleInfo.getHandles()){
                Handle handle = handleRepository.get(handleId);
                if(handle == null){
                    throw new ObjectNotExistException("操作资源不存在");
                }
            }
            AuthoInfo authoInfo = new AuthoInfo(assignRoleInfo.getProjectIdentify(), assignRoleInfo.getMenuIdnetify(),
                    assignRoleInfo.isAuthorize(), assignRoleInfo.getHandles());
            authoInfos.add(authoInfo);
        }
        RoleAutho roleAutho = new RoleAutho(role.getIdentity(), authoInfos, new Operator(operator, new Date()));

        roleAuthoRepository.add(roleAutho);
    }

}
